package com.example.barcodeapp.utils;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;

import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;

import com.example.barcodeapp.R;

import java.math.BigDecimal;



/**
 * Created by jed on 16/1/22.
 */
public class BBEditText extends EditText {
    private final static String TAG = "MyEditText";
    private Context mContext;
    private String value;       // 取值
    private String placeholder;   // 水印文字
    private boolean autoClear;  // 是否自动清空
    private boolean onTouch = true;

    public void setOnTouch(boolean onTouch) {
        this.onTouch = onTouch;
    }

    private boolean isShowClear = false;
    private Drawable mClearTextIcon;
    // 快捷商品结算 是否editText自行规整，不需要干涉
    private boolean editSelf = false;

    private String maxPrice;

    private int mNormalColor;
    private int mPressedColor;

    public final static int TWO_DECIMAL = 1 << 1;

    private int keyType;

    public void setIsShowClear(boolean isShowClear) {
        this.isShowClear = isShowClear;
    }

    public void setAutoClear(boolean autoClear) {
        this.autoClear = autoClear;
    }

    public BBEditText(Context context) {
        super(context);
        init(context);
    }

    public BBEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
        getAttrs(attrs);
    }

    public BBEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
        getAttrs(attrs);
    }

    private void getAttrs(AttributeSet attributeSet){
        TypedArray a = mContext.obtainStyledAttributes(
                attributeSet, R.styleable.BBEditText);
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            switch (attr) {
                case R.styleable.BBEditText_autoClear:{
                    autoClear = a.getBoolean(attr,false);
                }
                break;
                case R.styleable.BBEditText_isShowClear:{
                    isShowClear = a.getBoolean(attr,false);
                }
                break;
                default:
                    break;
            }
        }
        a.recycle();
    }

    public void setPlaceholder(String placeholder) {
        this.placeholder = placeholder;
        setHint(placeholder);
        value = placeholder;
    }

    public void setPlaceholder(@StringRes int resid) {
        setHint(getContext().getResources().getText(resid).toString());
    }

    public String getValue() {
        String str = getText().toString().trim();
        if (!TextUtils.isEmpty(str)){
            value = str;
        } else if (placeholder != null && !placeholder.isEmpty()){
            value = placeholder;
        } else {
            value = "";
        }
        return value;
    }

    public void setValue(String value) {
        this.value = value;
        if (TextUtils.isEmpty(placeholder)){
            setPlaceholder(value);
        }
    }

    @Override
    public Editable getText() {
        return super.getText();
    }

    private void init(final Context context) {
        mContext = context;
        final Drawable drawable = ContextCompat.getDrawable(context, R.drawable.cancel);
        mNormalColor = getResources().getColor(R.color.gray);

        mPressedColor = ColorUtil.darker(mNormalColor);

        final Drawable wrappedDrawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTint(wrappedDrawable, mNormalColor);
        mClearTextIcon = wrappedDrawable;
        mClearTextIcon.setBounds(0, 0, mClearTextIcon.getIntrinsicHeight(), mClearTextIcon.getIntrinsicHeight());

        setClearIconVisible(false);

        if (keyType == TWO_DECIMAL){
            setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        }
    }


    private void setClearIconVisible(final boolean visible) {
        if (isShowClear){
            mClearTextIcon.setVisible(visible, false);
            final Drawable[] compoundDrawables = getCompoundDrawables();
            setCompoundDrawables(
                    compoundDrawables[0],
                    compoundDrawables[1],
                    visible ? mClearTextIcon : null,
                    compoundDrawables[3]);
        }
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if (focused) {
            setClearIconVisible(getText().length() > 0);
        } else {
            setClearIconVisible(false);
        }
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {

        if (isFocused()) {
            setClearIconVisible(text.length() > 0);
        }
        if (onTouch){
            onTouch = false;
            if (autoClear){
                text = text.toString().subSequence(start,start + lengthAfter);
                setText(text);
                setSelection(getText().length());
            }
        }

        if (keyType == TWO_DECIMAL) {
            if (editSelf) {
                editSelf = false;
            } else {
                String string = text.toString();
                if (!getText().toString().equals(string)) {
                    editSelf = true;
                    setText(string);
                    setSelection(string.length());
                }
            }
        }

        if (!TextUtils.isEmpty(maxPrice) && !TextUtils.isEmpty(getValue())) {
            String string = getValue();
            try {
                if (!TextUtils.isEmpty(string)&&(new BigDecimal(string)).compareTo(new BigDecimal(maxPrice)) > 0) {
                    setText(maxPrice);
                    setSelection(getValue().length());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        super.onTextChanged(text, start, lengthBefore, lengthAfter);
    }

    private void setNoSendChangeText(String text){

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        onTouch = true;

        if (isShowClear){
            final int x = (int) event.getX();
            final int y = (int) event.getY();
            if (event.getAction() == MotionEvent.ACTION_UP) {
                DrawableCompat.setTint(mClearTextIcon, mNormalColor);
            }

            if (mClearTextIcon.isVisible() && x > getWidth() - getPaddingRight() - mClearTextIcon.getIntrinsicWidth() && x < getWidth() && y < getHeight() && y > 0) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    DrawableCompat.setTint(mClearTextIcon, mPressedColor);
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    setText("");
                    return true;
                }
            }
        }

        return super.onTouchEvent(event);
    }

    public void setKeyType(int keyType) {
        this.keyType = keyType;
        if (keyType == TWO_DECIMAL){
            setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        }
    }

    public void setMaxPrice(String maxPrice) {
        this.maxPrice = maxPrice;
    }


}
